const jwt = require('jsonwebtoken');
const { User } = require('../models');
const { Op } = require('sequelize');
const moment = require('moment');

// 生成JWT令牌
const generateToken = (userId) => {
  return jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: '7d' });
};

// 用户注册
const register = async (req, res) => {
  try {
    const { username, email, password, realName } = req.body;

    // 验证必填字段
    if (!username || !email || !password) {
      return res.status(400).json({ message: '用户名、邮箱和密码都是必填项' });
    }

    // 检查用户名是否已存在
    const existingUser = await User.findOne({
      where: { 
        [Op.or]: [{ username }, { email }] 
      }
    });

    if (existingUser) {
      return res.status(400).json({ 
        message: existingUser.username === username ? '用户名已存在' : '邮箱已被注册' 
      });
    }

    // 创建新用户
    const user = await User.create({
      username,
      email,
      password,
      real_name: realName
    });

    // 生成令牌
    const token = generateToken(user.id);

    res.status(201).json({
      message: '注册成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        realName: user.real_name,
        role: user.role,
        avatar: user.avatar
      }
    });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 用户登录
const login = async (req, res) => {
  try {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.status(400).json({ message: '用户名和密码都是必填项' });
    }

    // 查找用户
    const user = await User.findOne({
      where: {
        [Op.or]: [{ username }, { email: username }]
      }
    });

    if (!user) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 验证密码
    const isPasswordValid = await user.validatePassword(password);
    if (!isPasswordValid) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 检查账户状态
    if (user.status !== 'active') {
      return res.status(401).json({ message: '账户已被禁用，请联系管理员' });
    }

    // 更新最后登录时间
    await user.update({ last_login_at: new Date() });

    // 生成令牌
    const token = generateToken(user.id);

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        realName: user.real_name,
        role: user.role,
        avatar: user.avatar,
        totalStudyDays: user.total_study_days,
        continuousCheckinDays: user.continuous_checkin_days
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 获取当前用户信息
const getProfile = async (req, res) => {
  try {
    res.json({
      user: {
        id: req.user.id,
        username: req.user.username,
        email: req.user.email,
        realName: req.user.real_name,
        role: req.user.role,
        avatar: req.user.avatar,
        totalStudyDays: req.user.total_study_days,
        continuousCheckinDays: req.user.continuous_checkin_days,
        lastLoginAt: req.user.last_login_at
      }
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 更新用户信息
const updateProfile = async (req, res) => {
  try {
    const { realName, email } = req.body;
    const updateData = {};

    if (realName !== undefined) updateData.real_name = realName;
    if (email !== undefined) {
      // 检查邮箱是否已被其他用户使用
      const existingUser = await User.findOne({
        where: { email, id: { [Op.ne]: req.user.id } }
      });
      if (existingUser) {
        return res.status(400).json({ message: '邮箱已被其他用户使用' });
      }
      updateData.email = email;
    }

    await req.user.update(updateData);

    res.json({
      message: '个人信息更新成功',
      user: {
        id: req.user.id,
        username: req.user.username,
        email: req.user.email,
        realName: req.user.real_name,
        role: req.user.role,
        avatar: req.user.avatar
      }
    });
  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

module.exports = {
  register,
  login,
  getProfile,
  updateProfile
}; 